let server = require("express")();
let mysql = require('mysql');
// let expressStatic = require("express-static");
let multer = require('multer');


server.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200); //让options尝试请求快速结束
    else
        next();
})


let sql = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '123456',
    database: 'user',
    timezone: "08:00",
    port: 3306
});

// 尝试链接
sql.connect();

// 注册接口
// 引入加密模块
let crypto = require("crypto")
server.get("/zhuce/zhuce/user", function (request, response) {
    // 加密密码
    let newupwd = crypto.createHash('md5').update(request.query.upwd).digest('hex');
    var name = request.query.uname;
    var password = newupwd;
    var uid = request.query.uid
    sql.query(`SELECT * FROM demos WHERE uname="${name}"`, function (error, data) {
        if (error) {
            console.log(error)
            response.end("error")
            return
        }
        if (data.length === 0) {
            sql.query(`INSERT INTO demos (uname,upwd,uid) VALUES("${name}","${password}","${uid}")`, function (error, serve) {
                if (error) {
                    console.log(error)
                    response.end("error")
                    return
                } else {
                    response.end("success")
                }
            })
        } else {
            response.send("有了")
        }
    });
});
// 登陆接口
// post解析模块引用
let bodyParse = require("body-parser")
// 引入token
let jwt = require("jsonwebtoken")
// 使用解析模快
let uE = bodyParse.urlencoded({
    extended: false
})
server.post("/login/login/user", uE, function (request, response) {
    let newupwd = crypto.createHash('md5').update(request.body.upwd).digest('hex');
    var name = request.body.uname;
    sql.query(`SELECT * FROM demos WHERE uname="${name}"`, function (error, data) {
        let uid = data[0].uid
        if (data.length === 0) {
            response.send("没有注册,请注册")
            return;
        }
        if (data[0].upwd === newupwd) {    
            // 生成一个token
            let dataa = {
                userloginid: 1,
            }
            //密文
            let mi = "sakljhkjsdvkjasdbjks"
            //生成token
            var token = jwt.sign(dataa, mi);
            // 生成一个token
            response.send({
                deng: "可以登录",
                token: token,
                uid,
            })
        } else {
            response.send("出错了")
        }
    });
});
// 判断用户书否登录
server.post("/useertoken", uE, function (request, response) {
    sql.query(`SELECT * FROM demos`, (error, ok) => {
        if (error) {
            response.end("error")
            console.log(error)
            return
        } else {
            //密文
            let mi = "sakljhkjsdvkjasdbjks"
            // 解密
            jwt.verify(request.body.usertoken, mi, (err, data) => {
                if (data.userloginid == 1) {
                    response.send({
                        data: {
                            loginok: 1
                        }
                    })
                } else {
                    response.send({
                        data: {
                            loginok: 0
                        }
                    })
                }
            })
        }
    })

});
// 信息列表查询
server.get("/a", function (request, response) {
    sql.query(`SELECT * FROM demos`, (error, data) => {
        if (error) {
            response.end("error")
            console.log(error)
            return
        }
        response.send(JSON.stringify(data));
    })
})
// 图片上传
var storage = multer.diskStorage({
    //设置上传后文件路径，imgup文件夹会自动创建（建议手动提前创建这个文件夹）。
    destination: function (req, file, cb) {
        cb(null, './imgup')
    },
    //给上传文件重命名，获取添加后缀名
    filename: function (req, file, cb) {
        cb(null, "aa.jpg");
    }
});
var upload = multer({
    storage: storage
});
// 修改
server.post('/img/upload', upload.single('logo'), function (req, res, next) {
    // logo是前台向后台发送数据的key值 在传递数据的时候必须一样
    res.send({
        msg: '上传ok'
    });
});
server.post("/update", uE, (req, res) => {
    sql.query(`UPDATE demos SET uname='${req.body.uname}',upwd='${req.body.upwd}' WHERE uname='${req.body.oldname}' `, function (err, data) {
        if (err) {
            console.log(err);
        }
    })
})
// server.use(expressStatic(`${__dirname}/static`));
// 真正将上面的计划执行监听到本机的81端口上。
server.listen(3000)
console.log("3000端口已经打开")